package com.hoshiibuy.sku.service.impl;

import com.hoshiibuy.common.rpc.Response;
import com.hoshiibuy.sku.entity.AllocationSku;
import com.hoshiibuy.sku.entity.ExtSku;
import com.hoshiibuy.sku.feign.*;
import com.hoshiibuy.sku.mapper.AllocationSkuMapper;
import com.hoshiibuy.sku.service.AllocationSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiibuy.sku.service.ExtSkuService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hoshiibuy.common.aop.Logable;
import com.hoshiibuy.common.exception.CommonError;
import com.hoshiibuy.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

/**
 * <p>
 * SKU分配 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-05-05
 */
@Service
public class AllocationSkuServiceImpl extends ServiceImpl<AllocationSkuMapper, AllocationSku> implements AllocationSkuService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private SpuService spuService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private ExtSkuService extSkuService;
    /**
    * @param id
    * @return com.hoshiibuy.sku.entity.AllocationSku
    * @description: 根据id查询SKU分配
    */
    @Cacheable(cacheNames = "AllocationSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "SKU管理-SKU分配 -查询SKU分配 ")
    public AllocationSku getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
    * @param entity
    * @return boolean
    * @description: 新增SKU分配
    */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "AllocationSku", allEntries = true)
    @Logable(authName = "SKU管理-SKU分配-新增SKU分配")
    public boolean save(AllocationSku entity) {
        String id = idGeneratorService.queryGeneratorId();
        if (id == null || id == "") {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        if (entity.getSpuid()==null) {
            throw new ServiceException(CommonError.error("新增失败,SpuId不能为空"));
        }
        if (entity.getPlatformid()==null) {
            throw new ServiceException(CommonError.error("新增失败,平台ID不能为空"));
        }
        if (entity.getSkuid()==null) {
            throw new ServiceException(CommonError.error("新增失败,SkuId不能为空"));
        }

        Response response=spuService.getExtSpu(entity.getSpuid());
        if(response==null||response.getCode()!=200||response.getData()==null){
            throw new ServiceException(CommonError.error("新增失败，没有找到对应的SPU"));
        }


        response=platformService.getPlatForm(entity.getPlatformid());
        if(response==null||response.getCode()!=200||response.getData()==null){
            throw new ServiceException(CommonError.error("新增失败，没有找到对应的平台"));
        }

        if(entity.getStoreid()!=null){
            response=storeService.getStore(entity.getStoreid());
            if(response==null||response.getCode()!=200||response.getData()==null){
                throw new ServiceException(CommonError.error("新增失败，没有找到对应的门店"));
            }
        }
        ExtSku extSku =extSkuService.getById(entity.getId());
        if(extSku==null){
            throw new ServiceException(CommonError.error("新增失败，没有找到对应的Sku"));
        }

        //验证供应商是否存在 验证规则待确定
        // todo


        entity.setId(Long.parseLong(id));
        entity.setCreatedtime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
    * @param entity
    * @return boolean
    * @description: 修改SKU分配
    */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "AllocationSku", allEntries = true)
    @Logable(authName = "SKU管理-SKU分配管理-修改SKU分配")
    public boolean updateById(AllocationSku entity) {
        if(entity.getId()==null){
            throw new ServiceException(CommonError.error("修改失败,主键ID不能为空"));
        }

        if (entity.getSpuid()==null) {
            throw new ServiceException(CommonError.error("修改失败,SpuId不能为空"));
        }
        if (entity.getPlatformid()==null) {
            throw new ServiceException(CommonError.error("修改失败,平台ID不能为空"));
        }

        if (entity.getSkuid()==null) {
            throw new ServiceException(CommonError.error("修改失败,SkuId不能为空"));
        }

        Response response=spuService.getExtSpu(entity.getSpuid());
        if(response==null||response.getCode()!=200||response.getData()==null){
            throw new ServiceException(CommonError.error("修改失败，没有找到对应的SPU"));
        }


        response=platformService.getPlatForm(entity.getPlatformid());
        if(response==null||response.getCode()!=200||response.getData()==null){
            throw new ServiceException(CommonError.error("修改失败，没有找到对应的平台"));
        }

        if(entity.getStoreid()!=null){
            response=storeService.getStore(entity.getStoreid());
            if(response==null||response.getCode()!=200||response.getData()==null){
                throw new ServiceException(CommonError.error("修改失败，没有找到对应的门店"));
            }
        }
        ExtSku extSku =extSkuService.getById(entity.getId());
        if(extSku==null){
            throw new ServiceException(CommonError.error("修改失败，没有找到对应的Sku"));
        }

        //验证供应商是否存在 验证规则待确定
        // todo

        entity.setUpdatedtime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
    * @param queryWrapper
    * @return IPage
    * @description: 分页查询SKU分配
    */
    @Logable(authName = "SKU管理-SKU分配管理-分页查询SKU分配")
    @Cacheable(cacheNames = "AllocationSku", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5('Page(current=' + #page.getCurrent() + ', size=' + #page.getSize() + '), Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
    public IPage<AllocationSku> page(IPage<AllocationSku> page, Wrapper<AllocationSku> queryWrapper) {
        return baseMapper.selectPage(page, queryWrapper);
    }
}
